<template>
  <div class="wrapper">
    <img
      v-if="status !== ''"
      class="sign"
      :src="require(`./images/${status}.png`)"
    />
    <m-header title="送票信息">
      <template #icon>
        <m-iconfont
          classify="m-pc-public"
          icon="m-pc-public_jiesxx"
          color="#4d84ff"
        ></m-iconfont>
      </template>
    </m-header>
    <el-form
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
      class="demo-ruleForm"
    >
      <div v-if="isCreate" class="topSty">
        <el-form-item label="接收客户" prop="">
          <el-select
            v-model="form.customerCode"
            placeholder="请选择"
            @change="applyChange"
          >
            <el-option
              v-for="items in officList"
              :key="items.code"
              :label="items.name"
              :value="items.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接收科室" prop="">
          <el-select
            v-model="form.departCode"
            placeholder="请选择"
            @change="getReceptionAddress"
          >
            <el-option
              v-for="items in officListKS"
              :key="items.code"
              :label="items.name"
              :value="items.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接收地址" prop="">
          <el-select
            v-model="form.receiveAddressId"
            placeholder="请选择"
            @change="handleAddressChange"
          >
            <el-option
              v-for="items in receptionAddress"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接收人:" prop="hospitalCode">
          <el-input v-model="form.receivePersion" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话:" prop="hospitalShortName">
          <el-input v-model="form.contactPhone" disabled></el-input>
        </el-form-item>
        <el-form-item label="计划送票日期" prop="signingStatusStr">
          <el-date-picker
            v-model="form.giveBilingDate"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </div>
      <div v-else class="desc">
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="label">接收客户：</span>
            <span class="content">{{ form.customerName }}</span>
          </el-col>
          <el-col :span="8">
            <span class="label">接收科室：</span>
            <span class="content">{{ form.deparName }}</span>
          </el-col>
          <el-col :span="8">
            <span class="label">接收地址：</span>
            <span class="content">{{ form.receiveAddress }}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="label">接收人：</span>
            <span class="content">{{ form.receivePersion }}</span>
          </el-col>
          <el-col :span="8">
            <span class="label">联系电话：</span>
            <span class="content">{{ form.contactPhone }}</span>
          </el-col>
          <el-col :span="8">
            <span class="label">计划送票日期：</span>
            <span class="content">{{ form.giveBilingDate }}</span>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <m-header title="发票明细">
      <template #icon>
        <m-iconfont
          classify="m-pc-public"
          icon="m-pc-public_jiesxx"
          color="#4d84ff"
        ></m-iconfont>
      </template>
    </m-header>
    <div style="margin-top: 20px">
      <el-button
        v-if="isCreate || status === 3 || status === 1"
        icon="el-icon-plus"
        :style="{ marginBottom: 10 + 'px', marginLeft: 20 + 'px' }"
        @click="openBillModal"
        >新增发票</el-button
      >
      <m-editable
        v-loading="tableLoading"
        style="margin: 0 20px"
        :empty-type="resultType"
        :data="form.detailList"
        height="400"
        :style="{ height: 400 + 'px' }"
        :columns="cloumns"
      >
        <template
          v-if="isCreate || status === 3 || status === 1"
          slot="default-action"
          slot-scope="scope"
        >
          <el-button
            type="primary"
            plain
            size="mini"
            @click.stop="removeCell(scope.row)"
            >删除</el-button
          >
        </template>
      </m-editable>
    </div>
    <m-header title="签收信息">
        <template #icon>
          <m-iconfont
            classify="m-pc-public"
            icon="m-pc-public_jiesxx"
            color="#4d84ff"
          ></m-iconfont>
        </template>
      </m-header>
    <div v-if="status !== ''" class="signFor">
      <el-row type="flex" justify="start" style="margin-top: 20px">
        <div style="margin-right: 10px; width: 290px">签收回执单</div>
        <upload
          :class="{ hide: !canOperate }"
          :disabled="!canOperate"
          :headers="{ Authorization: token }"
          :action="ossUpload"
          :limit="9"
          :file-list="form.fileList"
          list-type="picture-card"
          accept="image/png,image/gif,image/jpg,image/jpeg"
          fit="scale-down"
          multiple
          :on-success="handleUploadSuccess"
          :on-remove="handleUploadRemove"
        >
          <div class="popup__m-dialog-upload">
            <m-iconfont
              classify="m-pc-public"
              icon="m-pc-public_tustjimg"
              size="14"
            />
            <p class="name">添加</p>
            <p>(请上传每张大小不超过5Mb的png、jpg文件,最多9张)</p>
          </div>
          <div slot="file" slot-scope="{ file }" class="file-actions">
            <div
              v-if="file && file.name && file.name.indexOf('pdf') !== -1"
              class="pdf"
            >
              <el-image
                fit="fill"
                :src="require('./images/pdf.png')"
                @click="toPreviewTwo(file, '查看附件')"
              />
            </div>
            <el-image v-else v-viewer fit="fill" :src="file.url" />
            <span
              v-if="canOperate"
              class="el-upload-list__item-delete"
              @click="handleUploadRemove(file)"
            >
              <i class="el-icon-delete"></i>
            </span>
            <!-- <span v-if="canOperate" class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-delete"
                @click="handleUploadRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span> -->
          </div>
        </upload>
      </el-row>
    </div>
    <div v-if="status === 3 || status === 4" class="audit">
      <h2>审核信息：</h2>
      <el-divider></el-divider>
      <m-editable
        style="margin: 0 20px"
        :empty-type="resultType"
        :data="form.logList"
        height="400"
        :style="{ height: 400 + 'px' }"
        :columns="logColumns"
      />
    </div>

    <div id="print" class="print">
      <h2>发票签收回执单</h2>
      <img class="qrcode" :src="qrcodeImg" />
      <p>
        请和对您收到的发票，确认无误后请在下表签收人一栏中签字（或盖章），谢谢配合！
      </p>
      <table class="define-table">
        <tr>
          <td width="200">收票单位</td>
          <td colspan="6">{{ form.customerName }}</td>
        </tr>
        <tr>
          <td>送票单位</td>
          <td colspan="6">{{ form.pcompanyName }}</td>
        </tr>
        <tr>
          <td>发票数量(张)</td>
          <td colspan="3">{{ form.detailList.length }}</td>
          <td width="200">送票日期</td>
          <td colspan="2">{{ form.giveBilingDate }}</td>
        </tr>
        <tr>
          <td>金额合计(元)</td>
          <td colspan="6">{{ sum }}</td>
        </tr>
        <tr>
          <td :rowspan="form.detailList.length + 1">发票号码及金额</td>
          <td>发票代码</td>
          <td>发票号码</td>
          <td>含税金额</td>
          <td>发票类型</td>
          <td>开票日期</td>
          <td>备注</td>
        </tr>
        <tr v-for="item in form.detailList" :key="item.giveApplyDetailId">
          <td>{{ item.invoiceCode }}</td>
          <td>{{ item.invoiceNumber }}</td>
          <td>{{ item.applicationAmount }}</td>
          <td>{{ item.invoiceTypeName }}</td>
          <td>{{ item.billingDateStr }}</td>
          <td>{{ item.remarks }}</td>
        </tr>
        <tr>
          <td height="100">备注</td>
          <td colspan="6"></td>
        </tr>
        <tr>
          <td height="50">签收单位(签收人)</td>
          <td colspan="3"></td>
          <td width="200">签收日期</td>
          <td colspan="2"></td>
        </tr>
      </table>
    </div>

    <bill-modal ref="billModal" :form-data="form" @done="handleBillSelect" />
  </div>
</template>

<script>
/* eslint-disable */

import QRCode from 'qrcode';
import {
  toQueryHospitalList,
  toQueryHospitalDepartList,
  getReceptionAddress,
  submitGiveInvoiceApply,
  toQuerySPList,
  toQuerySPDetailsList,
  confirmReceipt,
  againConfirmReceipt,
} from '@api/hossyn-order-center';
import { ossUpload } from '@pc/const/api_fileLibrary';
import BillModal from './components/BillModal';
import Upload from './components/upload';
import { columnsTableA } from './const';

export default {
  components: {
    BillModal,
    Upload,
  },
  data() {
    return {
      id: '',
      status: '',
      columnsTableA,
      logColumns: [
        {
          prop: 'statusStr',
          label: '审核结果',
          'show-overflow-tooltip': true,
          align: 'center',
        },
        {
          prop: 'remarks',
          label: '审核备注',
          'show-overflow-tooltip': true,
          align: 'center',
        },
        {
          prop: 'examineAt',
          label: '审核时间',
          'show-overflow-tooltip': true,
          align: 'center',
        },
      ],
      resultType: 0,
      tableLoading: false,
      officList: [],
      officListKS: [],
      receptionAddress: [],
      form: {
        customerName: '',
        customerCode: '',
        deparName: '',
        departCode: '',
        receiveAddressId: '',
        receivePersion: '',
        receiveAddress: '',
        contactPhone: '',
        detailList: [],
        fileList: [],
        logList: [],
      },
      qrcodeImg: '',
      ossUpload,
      token: `Bearer ${this.$store.state.token}`,
    };
  },
  computed: {
    isCreate() {
      return this.id === '';
    },
    canOperate() {
      return this.status === 1 || this.status === 3;
    },
    sum() {
      let sum = 0;
      this.form.detailList.forEach((item) => {
        sum += item.applicationAmount;
      });
      return sum;
    },
    cloumns() {
      return this.columnsTableA.filter((item) => {
        if (this.status === 2 || this.status === 4) {
          return item.prop !== 'action';
        }
        return true;
      });
    },
  },
  created() {
    if (this.$route.query.giveApplyId && !this.$route.query.row) {
      this.id = this.$route.query.giveApplyId;
      this.status = Number(this.$route.query.status);
      this.toQuerySPMethod();
      this.toQuerySPDetailsListMethod();
      this.createQR();
    } else {
      this.toQueryHospitalListMethod();
      if (this.$route.query.row) {
        const rows = JSON.parse(this.$route.query.row);
        this.form.customerName = rows[0].customerName;
        this.form.customerCode = rows[0].customerCode;
        this.form.detailList = rows;
        this.toQueryHospitalDepartListMethod(rows[0].customerCode);
      }
    }
  },
  mounted() {
    const obj = {
      type: 'btn',
      arr: [],
    };
    const status = Number(this.$route.query.status);
    if (this.id === '') {
      obj.arr.push({ type: 'primary', val: '提交', handle: this.onSubmit });
    }

    if (status === 1) {
      obj.arr.push({
        type: 'primary',
        val: '确认签收',
        handle: this.signFor,
      });
    }

    if (status === 3) {
      obj.arr.push({
        type: 'primary',
        val: '重新签收',
        handle: () => this.resignfor(2),
      });
      // obj.arr.push({
      //   type: 'primary',
      //   val: '保存',
      //   handle: () => this.resignfor(2),
      // });
    }

    if (status === 1 || status === 3) {
      obj.arr.push({
        type: 'primary',
        val: '打印回执单',
        handle: this.handlePrint,
      });
    }
    this.$store.commit('changeLayoutHandle', obj);
  },
  methods: {
    createQR() {
      QRCode.toDataURL(`https://md.heng-tai.com.cn/?sid=${this.id}`)
        .then((url) => {
          this.qrcodeImg = url;
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '生成二维码失败，建议使用本地上传！',
          });
        });
    },
    openBillModal() {
      this.$refs.billModal.open();
    },
    toPreviewTwo(item, title) {
      this.$pdfViewer({
        url: item.url,
        title,
      });
    },
    handleBillSelect(e) {
      const arr = this.form.detailList.concat(e);
      const obj = {};
      const result = arr.reduce((prev, cur, index, array) => {
        obj[cur.invoiceCode]
          ? ''
          : (obj[cur.invoiceCode] = true && prev.push(cur));
        return prev;
      }, []);
      this.form.detailList = result;
    },
    handleAddressChange(e) {
      const currentItem = this.receptionAddress.find(
        (item) => item.value === e
      );
      if (currentItem) {
        this.form.receivePersion = currentItem.linkMan;
        this.form.contactPhone = currentItem.linkPhone;
        this.form.receiveAddress = currentItem.address;
      }
    },
    toQueryHospitalListMethod() {
      this.$axios({
        url: toQueryHospitalList,
        method: 'post',
        data: {},
      })
        .then((res) => {
          this.officList = res.data.payload || [];
        })
        .catch((err) => {});
    },
    applyChange(e) {
      if (this.$route.query.giveApplyId && !this.$route.query.row) {
        this.$confirm('此操作将清空列表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.form = {
              customerName: '',
              customerCode: e,
              deparName: '',
              departCode: '',
              receiveAddressId: '',
              receivePersion: '',
              receiveAddress: '',
              contactPhone: '',
              detailList: [],
              fileList: [],
              logList: [],
            };
            this.toQueryHospitalDepartListMethod(e);
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      } else {
        this.toQueryHospitalDepartListMethod(e);
      }
    },
    //  科室toQueryHospitalDepartList
    toQueryHospitalDepartListMethod(code) {
      // this.form.departCode = '';
      // this.form.receiveAddressId = '';

      const officeItem = this.officList.find((item) => item.code === code);
      if (officeItem) {
        this.form.customerName = officeItem.name;
      }

      this.$axios({
        url: toQueryHospitalDepartList,
        method: 'post',
        data: {
          hospitalCode: code,
        },
      })
        .then((res) => {
          this.officListKS = res.data.payload || [];
        })
        .catch((err) => {});
    },
    removeCell(row) {
      this.form.detailList = this.form.detailList.filter(
        (item) => item.invoiceCode !== row.invoiceCode
      );
    },
    handleUploadSuccess(response, file, fileList) {
      this.form.fileList = fileList.map((item) => {
        let tempItem = {};
        if (item.response) {
          tempItem = {
            name: item.response.payload.fileName,
            url: item.response.payload.fileUrl,
            ...item.response.payload,
          };
        } else {
          tempItem = {
            name: item.fileName,
            url: item.fileUrl,
            ...item,
          };
        }
        return tempItem;
      });
    },
    handleUploadRemove(file) {
      this.form.fileList = this.form.fileList.filter(
        (item) => item.name !== file.name
      );
    },
    async getReceptionAddress(code) {
      this.form.receiveAddressId = '';
      const officeKSItem = this.officListKS.find((item) => item.code === code);
      if (officeKSItem) {
        this.form.deparName = officeKSItem.name;
      }
      const { data } = await this.$axios({
        url: getReceptionAddress,
        method: 'post',
        data: {
          hospitalCode: this.form.customerCode,
          departCode: code,
        },
      });

      const address = [];
      data.payload.forEach((item) => {
        address.push({
          label: item.province + item.city + item.county,
          value: item.recevieAddressId,
          linkMan: item.linkMan,
          linkPhone: item.linkPhone,
          address: item.address,
        });
      });
      this.receptionAddress = address;
    },
    // 送票详情giveApplyCode
    toQuerySPMethod() {
      this.$axios({
        url: toQuerySPList,
        method: 'post',
        data: {
          giveApplyId: this.id,
        },
      })
        .then((res) => {
          const { payload } = res.data;
          this.form.customerCode = payload.customerCode;
          this.form.customerName = payload.customerName;
          this.form.departCode = payload.departCode;
          this.form.deparName = payload.deparName;
          this.form.receiveAddressId = payload.receiveAddressId;
          this.form.receivePersion = payload.receivePersion;
          this.form.receiveAddress = payload.receiveAddress;
          this.form.contactPhone = payload.contactPhone;
          this.form.giveBilingDate = payload.giveBilingDate;
          this.form.giveApplyId = payload.giveApplyId;
          this.form.giveApplyCode = payload.giveApplyCode;
          this.form.fileList = payload.fileList.map((item) => ({
            ...item,
            name: item.fileName,
            url: item.fileUrl,
          }));
          this.form.logList = payload.logList;
          this.form.pcompanyName = payload.pcompanyName;
          this.form.pcompanyCode = payload.pcompanyCode;
          this.form.remarks = payload.remarks;
        })
        .catch((err) => {});
    },
    //  明细列表
    toQuerySPDetailsListMethod() {
      this.tableLoading = true;
      this.$axios({
        url: toQuerySPDetailsList,
        method: 'post',
        data: {
          giveApplyId: this.id,
          // page: this.page.curPage,
          // pageSize: this.page.pageSize,
        },
      })
        .then((res) => {
          this.form.detailList = res.data.payload.content || [];
          // this.dataList = res.data.payload.content || [];
          // this.page.total = res.data.payload.totalElements;
          // if (this.page.total == 0) {
          //   this.paging = false;
          // }
          this.tableLoading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async onSubmit() {
      const result = await this.$axios({
        url: submitGiveInvoiceApply,
        method: 'post',
        data: this.form,
      });
      if (result) {
        this.$message.success('提交成功');
        this.$router.back();
      }
    },
    async signFor() {
      if (!this.form.fileList.length) {
        this.$message.info('请上传签收信息!');
        return;
      }
      const result = await this.$axios({
        url: confirmReceipt,
        method: 'post',
        // data: this.form,
        data: {
          giveApplyId: this.id,
          detailList: this.form.detailList,
          fileList: this.form.fileList.map((item) => ({
            fileName: item.fileName,
            fileUrl: item.fileUrl,
          })),
        },
      });
      if (result) {
        this.$message.success('签收成功');
        this.$router.back();
      }
    },
    async resignfor(status) {
      if (!this.form.fileList.length) {
        this.$message.info('请上传签收信息!');
        return;
      }
      const result = await this.$axios({
        url: againConfirmReceipt,
        method: 'post',
        data: {
          aginStatus: status,
          giveApplyId: this.id,
          detailList: this.form.detailList,
          remarks: this.form.remarks,
          fileList: this.form.fileList.map((item) => ({
            fileName: item.fileName,
            fileUrl: item.fileUrl,
          })),
        },
      });
      if (result) {
        this.$message.success('签收成功');
        this.$router.back();
      }
    },
    handlePrint() {
      window.print();
      // const printDom = document.getElementById('print').innerHTML;
      // const w = window.open(location.href);
      // w.document.body.innerHTML = printDom;
      // const style = w.document.createElement('style');
      // style.type = 'text/css';
      // style.innerText = `
      //   .print {
      //     display: block;
      //   }
      //   .print h2 {
      //     margin-bottom: 50px;
      //     text-align: center;
      //   }
      //   .print .define-table {
      //     width: 100%;
      //     border-collapse: collapse;
      //     border-spacing: 0;
      //     border-left: 1px solid #888;
      //     border-top: 1px solid #888;
      //   }
      //   .print .define-table th,
      //   .print .define-table td {
      //     border-right: 1px solid #888;
      //     border-bottom: 1px solid #888;
      //     padding: 5px 15px;
      //     text-align: center;
      //     vertical-align: middle;
      //   }
      //   .print .define-table th {
      //     font-weight: bold;
      //     background: #ccc;
      //   }
      // `;
      // w.document.getElementsByTagName('head').item(0).appendChild(style);
      // w.document.close();
      // w.print();
      // w.close();
    },
  },
};
</script>

<style lang="less">
.desc {
  margin: 20px 20px 66px;
  .el-row {
    margin-bottom: 20px;
  }
  .label {
    font-size: 14px;
    color: #666666;
  }
  .content {
    font-size: 14px;
    color: #333333;
  }
}
.signFor {
  margin: 20px 20px;
  h2,
  .el-divider {
    margin-left: -20px;
  }
}
.wrapper {
  position: relative;
  .sign {
    position: absolute;
    top: 50px;
    right: 50px;
  }
}
.el-upload,
.el-upload-list__item {
  width: 220px !important;
  height: 150px !important;
}
.el-upload-list__item > div {
  height: 100%;
  .el-image {
    height: 100%;
  }
}
.hide .el-upload--picture-card {
  display: none;
}
.file-actions {
  position: relative;
  .el-upload-list__item-delete {
    position: absolute;
    right: 10px;
    top: 5px;
    display: block;
    color: red;
  }
  .el-image {
    width: 100%;
    height: 100%;
  }
}
.popup__m-dialog-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  line-height: initial;
  height: 100%;
  i {
    color: #85aafd;
    border: 1px solid #85aafd;
    width: 42px;
    height: 42px;
    line-height: 42px;
    font-size: 40px;
    font-weight: bold;
    border-radius: 50%;
    margin-bottom: 10px;
  }
  .name {
    // margin-top: 10px;
    margin-bottom: 5px;
  }
  p {
    font-size: 12px;
    text-align: center;
    color: #999999;
  }
}
.circular {
  margin: 0 auto;
}
.pdf {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-image {
    width: 100px;
    height: auto !important;
  }
}

.print {
  position: relative;
  display: none;
  h2 {
    margin-bottom: 30px;
    text-align: center;
  }
  p {
    margin-bottom: 5px;
  }
  .qrcode {
    position: absolute;
    top: 0;
    right: 0;
    width: 50px;
    height: 50px;
  }
  .define-table {
    width: 100%;
    border-collapse: collapse;
    border-spacing: 0;
    border-left: 1px solid #888;
    border-top: 1px solid #888;
  }
  .define-table th,
  .define-table td {
    border-right: 1px solid #888;
    border-bottom: 1px solid #888;
    padding: 5px 15px;
    text-align: center;
    vertical-align: middle;
  }
  .define-table th {
    font-weight: bold;
    background: #ccc;
  }
}

@media print {
  .aside-menu,
  .nav-breadcrumb,
  .nav-box-header,
  .wrapper > :not(.print) {
    display: none !important;
  }
  .print {
    display: block;
  }
}

@page {
  size: auto; /* auto is the initial value */
  margin: 0mm; /* this affects the margin in the printer settings */
}
</style>
